package com.ithaipeng.redanttakeaway.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ithaipeng.redanttakeaway.pojo.User;
import com.ithaipeng.redanttakeaway.service.IUserService;
import com.ithaipeng.redanttakeaway.tools.Result;
import com.ithaipeng.redanttakeaway.tools.SMSUtils;
import com.ithaipeng.redanttakeaway.tools.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 发送验证码!
     * @param user
     * @param httpSession
     * @return
     */
    @PostMapping("/sendMsg")
   public Result<String> sendMsg(@RequestBody User user, HttpSession httpSession){
        //先获取手机号
        String userPhone = user.getPhone();
        //生成随机的6味验证码
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("code-->{}",code);
        httpSession.setAttribute(userPhone,code);
        SMSUtils.sendMessage("菩提阁","SMS_288455486",userPhone,code);
        return Result.success("短信验证成功");
   }

    /**
     * 用户登录!
     * @param map
     * @param httpSession
     * @return
     */
    @PostMapping("/login")
   public Result<String> login(@RequestBody Map map,HttpSession httpSession){
        log.info("map:-->{}",map.toString());
        String code=map.get("code").toString();
        String phoneNumber=map.get("phone").toString();
       Object codeSession = httpSession.getAttribute(phoneNumber);
       if(codeSession!=null&&codeSession.equals(code)){
           LambdaQueryWrapper<User> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
           userLambdaQueryWrapper.eq(User::getPhone,phoneNumber);
           User user = userService.getOne(userLambdaQueryWrapper);
           if (user==null){
               user=new User();
               user.setPhone(phoneNumber);
               user.setStatus(1);
               userService.save(user);
           }
           httpSession.setAttribute("userId",user.getId());
           return Result.success("用户登录成功");
       }
       return Result.error("用户登录失败!");
   }
   @PostMapping("/loginout")
   public Result<String> loginout(HttpSession httpSession){
        httpSession.removeAttribute("userId");
        return Result.success("成功退出!");
   }
}
